package services

import (
	"errors"
	"fmt"
	database "hft/Database"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
)

type SwiperCategory struct{}

func (*SwiperCategory) CreateCategory(category *request.SwiperCategory) (err error) {

	if category.Type != 1 && category.Type != 2 {
		return errors.New("无效的类型")
	}

	var newCate = &admin.LouPanSwiperCategory{
		IsShow:  category.IsShow,
		Name:    category.Name,
		Type:    category.Type,
		Base:    database.Base{Sort: category.Sort},
		IsCover: category.IsCover,
	}

	res := global.OC_DB.Where("name = ? AND type = ?", category.Name, category.Type).FirstOrCreate(&newCate)

	if res.Error != nil {
		return errors.New("未知错误500")
	}
	if res.RowsAffected == 0 {
		return errors.New("分类已存在")
	}

	return nil
}

func (*SwiperCategory) EditCategory(category *request.SwiperCategory) (err error) {

	fmt.Println(tools.JsonParse(category))

	if category.Type != 1 && category.Type != 2 {
		return errors.New("无效的类型")
	}

	var newCate = &admin.LouPanSwiperCategory{
		Type:    category.Type,
		IsShow:  category.IsShow,
		Name:    category.Name,
		Base:    database.Base{ID: category.ID, Sort: category.Sort},
		IsCover: category.IsCover,
	}

	err = global.OC_DB.Where("id = ?", category.ID).Omit("create_time,update_time,deleted_at").Save(&newCate).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*SwiperCategory) GetCategoryList(paginate *request.SwiperCategoryPage) (data *utils.Page, err error) {

	var newCategoryList []*admin.LouPanSwiperCategory

	err = global.OC_DB.Scopes(dao.SwiperCategoryDao.GetCategoryList(paginate.Type, global.OC_DB)).Scopes(dao.Paginate(dao.Page(paginate.Page), global.OC_DB)).Order("sort desc").Find(&newCategoryList).Offset(-1).Limit(-1).Count(&paginate.Total).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	paginate.Data = newCategoryList

	return &paginate.Page, nil
}

var SwiperCategoryServices = new(SwiperCategory)
